package ua.com.hackaton;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import ua.com.hackaton.core.MyData;
import ua.com.hackaton.core.Settings;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Eugene Borshch
 * Date: 6/25/11
 * Time: 10:56 PM
 * To change this template use File | Settings | File Templates.
 */
public class MainActivity extends Activity
{
    public static final boolean SPLIT_FULL_NAME = true;
    Facebook facebook = new Facebook("244565025554051");

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ImageButton androidBtn = (ImageButton) findViewById(R.id.android);
        androidBtn.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                Map<String, Integer> callData = fetchCallData();

                Intent myIntent = new Intent(MainActivity.this, CloudMeActivity.class);

                MyData parcel = new MyData(callData);
                myIntent.putExtra("data", parcel);
                startActivity(myIntent);
            }

        });


        ImageButton facebookBtn = (ImageButton) findViewById(R.id.facebook);
        facebookBtn.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                facebook.authorize(MainActivity.this, new String[]{"email", "read_mailbox"}, new Facebook.DialogListener()
                {
                    @Override
                    public void onComplete(Bundle values)
                    {
                        //get information about the currently logged in user
                        Map<String, Integer> callData = loadMessagesInfo();
                        Intent myIntent = new Intent(MainActivity.this, CloudMeActivity.class);

                        MyData parcel = new MyData(callData);
                        myIntent.putExtra("data", parcel);
                        startActivity(myIntent);
                    }

                    @Override
                    public void onFacebookError(FacebookError error)
                    {
                    }

                    @Override
                    public void onError(DialogError e)
                    {
                    }

                    @Override
                    public void onCancel()
                    {
                    }
                });


            }

        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        facebook.authorizeCallback(requestCode, resultCode, data);
    }


    private Map<String, Integer> fetchCallData()
    {
        Map<String, Integer> result = new HashMap<String, Integer>();
        Uri allCalls = Uri.parse("content://call_log/calls");
        Cursor c = managedQuery(allCalls, null, null, null, null);
        for (String colName : c.getColumnNames())
            Log.v("Log", "Column Name: " + colName);

        if (c.moveToFirst())
        {
            do
            {
                String name = c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));
                if (name != null)
                {
                    onMessageFrom(name, result);
                }

            } while (c.moveToNext());
        }
        return result;
    }

    protected Map<String, Integer> loadMessagesInfo()
    {
        Map<String, Integer> nameToNumberOfMessagesMap = null;
        try
        {
            String personalInfo = facebook.request("me");
            String userName = parseUserName(personalInfo);

            String inbox = facebook.request("me/inbox");
            nameToNumberOfMessagesMap = parseInbox(inbox);
            nameToNumberOfMessagesMap.remove(userName);

            // TODO pass this data to the listener
        } catch (MalformedURLException e1)
        {
            Log.v("exception", e1.getLocalizedMessage());
        } catch (IOException e1)
        {
            Log.v("exception", e1.getLocalizedMessage());
        }
        return nameToNumberOfMessagesMap;
    }

    private String parseUserName(String personalInfo)
    {
        int nameIndex = personalInfo.indexOf("\"name\"") + "\"name\"".length() + ":\"".length();
        return personalInfo.substring(nameIndex, personalInfo.indexOf("\"", nameIndex));
    }

    private static Map<String, Integer> parseInbox(String inbox)
    {
        Map<String, Integer> result = new HashMap<String, Integer>();
        String currentString = inbox;
        int currentIndex = 0;
        int startIndex = 0;
        int endIndex = 0;
        do
        {
            currentIndex = currentString.indexOf("\"from\"");
            currentString = currentString.substring(currentIndex);
            startIndex = currentString.indexOf("\"name\"")
                    + "\"name\"".length() + ":\"".length();
            endIndex = currentString.indexOf("\"", startIndex);
            String name = currentString.substring(startIndex, endIndex);

            currentString = currentString.substring(endIndex);
            if (name.contains("\\u"))
                continue;
            if (name.contains(" ") && SPLIT_FULL_NAME)
            {
                String firstName = name.substring(0, name.indexOf(" "));
                String secondName = name.substring(name.indexOf(" ") + " ".length());
                onMessageFrom(firstName, result);
                onMessageFrom(secondName, result);
            } else
            {

                onMessageFrom(name, result);
            }

        } while (currentString.contains("\"from\""));

        return result;
    }

    private static void onMessageFrom(String name, Map<String, Integer> result)
    {
        Integer numMessages = result.get(name);
        if (numMessages == null)
        {
            numMessages = 0;
        }
        numMessages++;
        result.put(name, numMessages);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_settings, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle item selection
        switch (item.getItemId())
        {
            case R.id.settings:
                final CharSequence[] items = {Settings.Pack.PACK1.toString(), Settings.Pack.PACK2.toString(),Settings.Pack.PACK3.toString()};

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Pick color scheme");
                builder.setItems(items, new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int item)
                    {
                        switch (item)
                        {
                            case 0:
                                CloudMeActivity.settings = Settings.getSettings(Settings.Pack.PACK1);
                                break;
                             case 1:
                                CloudMeActivity.settings = Settings.getSettings(Settings.Pack.PACK2);
                                break;
                              case 2:
                                CloudMeActivity.settings = Settings.getSettings(Settings.Pack.PACK3);
                                break;
                        }
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}